package com.xbk.seckill.reservation.application.event;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbk.seckill.common.constants.SeckillConstants;
import com.xbk.seckill.reservation.application.cache.SeckillReservationConfigCacheService;
import com.xbk.seckill.reservation.domain.event.SeckillReservationConfigEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * 基于RocketMQ的商品事件处理器
 *
 * @author xiexu
 * @date 2025/4/24 08:14
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "message.mq.type", havingValue = "rocketmq")
@RocketMQMessageListener(consumerGroup = SeckillConstants.EVENT_RESERVATION_CONFIG_CONSUMER_GROUP, topic = SeckillConstants.TOPIC_EVENT_ROCKETMQ_RESERVATION_CONFIG)
public class SeckillReservationConfigRocketMQEventHandler implements RocketMQListener<String> {

    @Autowired
    private SeckillReservationConfigCacheService seckillReservationConfigCacheService;

    @Override
    public void onMessage(String message) {
        log.info("rocketmq|reservationConfigEvent|接收秒杀品预约配置事件|{}", message);
        if (StrUtil.isEmpty(message)) {
            log.info("rocketmq|reservationConfigEvent|接收秒杀品预约配置事件参数错误");
            return;
        }
        // 解析消息
        SeckillReservationConfigEvent seckillReservationConfigEvent = this.getEventMessage(message);
        if (seckillReservationConfigEvent == null) {
            log.info("rocketmq|reservationConfigEvent|解析后的数据为空");
            return;
        }
        log.info("rocketmq|reservationConfigEvent|接收秒杀品预约配置事件解析后的数据|{}", JSON.toJSONString(seckillReservationConfigEvent));
        // 更新商品预约配置缓存
        seckillReservationConfigCacheService.tryUpdateSeckillReservationConfigCacheByLock(seckillReservationConfigEvent.getId(), false);
        // 更新预约配置列表
        seckillReservationConfigCacheService.tryUpdateSeckillReservationConfigListCacheByLock(false);
    }

    private SeckillReservationConfigEvent getEventMessage(String msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String eventStr = jsonObject.getString(SeckillConstants.MSG_KEY);
        return JSONObject.parseObject(eventStr, SeckillReservationConfigEvent.class);
    }

}
